package com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.aibkMarkZw

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.AnimationDrawable
import android.os.Environment
import android.text.Editable
import android.text.Html
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.auidoPlayer.AudioTracker
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseRecyclerAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseRecyclerViewHolder
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.ItemXMark
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.AibkQuesMarkActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.ChangeListener
import com.lancoo.znbkxx.teacher.aibkTestCoach.questionToMark.adapter.ZwPhotoAdapter
import com.lancoo.znbkxx.teacher.utils.GlideEngine
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.utils.ToastUtils
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.entity.LocalMedia
import java.math.BigDecimal
import java.math.BigDecimal.ROUND_HALF_UP
import java.math.BigDecimal.ZERO
import java.math.RoundingMode
import java.text.DecimalFormat

class MarkFragmentZwChildView(private val mActivity: AibkQuesMarkActivity, private var mAudioTracker: AudioTracker? = null, private val childAnswerList: MutableList<ItemXMark>) : KBaseRecyclerAdapter() {

    private lateinit var scView: NestedScrollView
    private lateinit var rvPhoto: RecyclerView
    private lateinit var photoAdapter: ZwPhotoAdapter
    private lateinit var llAudio: LinearLayout
    private lateinit var ivAudio: ImageView
    private lateinit var tvText: TextView
    private lateinit var tvComment: TextView
    private lateinit var tvNoScore: TextView
    private lateinit var llScore: LinearLayout
    private lateinit var etScore: EditText
    private lateinit var llComment: LinearLayout
    private lateinit var rlText: ConstraintLayout
    private lateinit var tvUnitScore: TextView
    private lateinit var tvName: TextView
    private lateinit var changeListener: ChangeListener

    private val audioPaths: ArrayList<String> = ArrayList()
    private var onItemClickListener: OnItemClickListener? = null

    private var animationDrawable: Array<AnimationDrawable?> = arrayOfNulls<AnimationDrawable>(childAnswerList.size)

    override fun getHolderView(parent: ViewGroup?, position: Int): View? {
        return LayoutInflater.from(mActivity).inflate(R.layout.layout_mark, parent, false)
    }

    override fun onBindViewHolder(holder: KBaseRecyclerViewHolder, position: Int) {
        tvName = holder.itemView.findViewById(R.id.tv_name)
        llAudio = holder.itemView.findViewById(R.id.ll_audio)
        ivAudio = holder.itemView.findViewById(R.id.iv_audio)
        scView = holder.itemView.findViewById(R.id.sc_view)
        rvPhoto = holder.itemView.findViewById(R.id.rv_photo)
        tvText = holder.itemView.findViewById(R.id.tv_text)
        tvComment = holder.itemView.findViewById(R.id.tv_comment)
        tvNoScore = holder.itemView.findViewById(R.id.tv_no_score)
        llScore = holder.itemView.findViewById(R.id.ll_score)
        etScore = holder.itemView.findViewById(R.id.et_score)
        llComment = holder.itemView.findViewById(R.id.ll_comment)
        rlText = holder.itemView.findViewById(R.id.rl_text)
        tvUnitScore = holder.itemView.findViewById(R.id.tv_unit_score)
        tvName.text = childAnswerList[position].StuName
        //作文
        //判断是否有图，有图则不显示其他
        setAudioList(position)
        judgeEval(llComment, etScore, position)
        if (!showPhoto(position)) {
            showText(position)
            showAudio(ivAudio, position)
        }
        showComment(tvComment, position)
    }

    private fun showComment(tvComment: TextView, position: Int) {
        val comment: String = childAnswerList[position].Comment
        if (comment.isNotEmpty()) {
            tvComment.text = Html.fromHtml(mActivity.resources.getString(R.string.wxd_031, comment))
        }
    }

    private fun judgeEval(llComment: LinearLayout, etScore: EditText, position: Int) {
        if (childAnswerList[position].State == 3) {
            notEval(position)
        } else {
            eval(position)
            doEvalJob(llComment, etScore, position)
        }
    }

    //照片答案
    private fun showPhoto(position: Int): Boolean {
        val imagePath: String = childAnswerList[position].ImagePath
        if (imagePath.isEmpty()) {
            scView.visibility = View.GONE
            rvPhoto.visibility = View.GONE
            rlText.visibility = View.VISIBLE
            return false
        } else {
            scView.visibility = View.VISIBLE
            rvPhoto.visibility = View.VISIBLE //VISIBLE
            rlText.visibility = View.GONE
            val gridLayoutManager = GridLayoutManager(mActivity, 3)
            rvPhoto.layoutManager = gridLayoutManager
            photoAdapter = ZwPhotoAdapter(mActivity)
            val imagePathListSize = LancooUtils.getStringFrequency(imagePath, "|") + 1
            val selectList: MutableList<LocalMedia> = ArrayList()
            selectList.clear()
            if (imagePathListSize >= 1) {
                for (i in 0 until imagePathListSize) {
                    val media = LocalMedia()
                    media.path = Ext.OBSINFO!!.ServerWithBucket + LancooUtils.returnArray(imagePath, "|", 1)[i] //UserInfoBean
                    selectList.add(i, media)
                }
            }
            photoAdapter.setList(selectList)
            photoAdapter.isShowDelectIcon = false
            photoAdapter.setSelectMax(9)
            photoAdapter.setOnItemClickListener { itemPosition, _ ->
                if (selectList.size > 0) {
                    val media = selectList[itemPosition]
                    val pictureType = media.mimeType
                    if (pictureType.contains("image")) {
                        PictureSelector.create(mActivity)
                                .themeStyle(R.style.picture_default_style)
                                .imageEngine(GlideEngine.createGlideEngine())
                                .openExternalPreview(itemPosition, selectList);
                    }
                }
            }
            rvPhoto.adapter = photoAdapter
        }
        return true
    }

    private fun setAudioList(position: Int) {
        val audioPath: String = childAnswerList[position].AudioPath
        if (audioPath.isEmpty()) {
            audioPaths.add("")
        } else {
            val downLoadUrl: String = Ext.OBSINFO!!.ServerWithBucket + audioPath
            val i = downLoadUrl.lastIndexOf("/")
            val audioName = downLoadUrl.substring(i + 1)
            mAudioTracker?.downLoadAudio(downLoadUrl, audioName)
            audioPaths.add(Environment.getExternalStorageDirectory().absolutePath.toString() + "/Android/data/com.lancoo.znbkxx.teacher/" + "files/audio/" + audioName)
        }
    }

    //音频答案 音频无法播放问题
    private fun showAudio(ivAudio: ImageView, position: Int) {
        val audioPath: String = childAnswerList[position].AudioPath
        if (audioPath.isEmpty()) {
            llAudio.visibility = View.GONE
        } else {
            llAudio.visibility = View.VISIBLE //VISIBLE
            ivAudio.setImageResource(R.drawable.anim_laba)
            animationDrawable[position] = ivAudio.drawable as AnimationDrawable // 1. 获取动画对象
            ivAudio.setOnClickListener {
                if (audioPaths[position].isNotEmpty()) {
                    animationDrawable[position]?.start()
                    mAudioTracker?.setMFilePath(audioPaths[position])
                    mAudioTracker?.start()
                    for (j in 0 until childAnswerList.size) {
                        if (j != position) {
                            if (animationDrawable[j] != null) {
                                animationDrawable[j]!!.selectDrawable(0)
                                animationDrawable[j]!!.stop()
                            }
                        }
                    }
                }
                mAudioTracker?.setPlayListener(object : AudioTracker.PlayListener {
                    override fun playPrepare() {
                    }

                    override fun playStart() {

                    }

                    override fun playFinish() {
                        mActivity.runOnUiThread {
                            animationDrawable[position]!!.selectDrawable(0)
                            animationDrawable[position]?.stop()
                        }
                    }
                })
            }
        }
    }

    //文字答案
    private fun showText(position: Int) {
        val textAnswer: String = childAnswerList[position].StuAnswer
        if (textAnswer.isEmpty()) {
            tvText.text = "未填写"
        } else {
            tvText.text = textAnswer
        }
    }


    //不需要评阅
    private fun notEval(position: Int) {
        llScore.visibility = View.GONE
        tvNoScore.visibility = View.VISIBLE
        llComment.background = mActivity.resources.getDrawable(R.drawable.bg_subject_view)
        tvNoScore.text = "${childAnswerList[position].EvalScore} 分(满分" + DecimalFormat("#,##0.00").format(childAnswerList[position].TotalScore).toString() + "分)"
    }

    //需要评阅
    private fun eval(position: Int) {
        tvNoScore.visibility = View.GONE
        llScore.visibility = View.VISIBLE
        if (childAnswerList[position].State == 0 || childAnswerList[position].State == 1) {
            llComment.background = mActivity.resources.getDrawable(R.drawable.bg_comment_view)
        } else {
            llComment.background = mActivity.resources.getDrawable(R.drawable.bg_subject_view)
        }
        etScore.setText(DecimalFormat("#,##0.00").format(childAnswerList[position].EvalScore).toString())
        tvUnitScore.text = "分(满分" + DecimalFormat("#,##0.00").format(childAnswerList[position].TotalScore).toString() + "分)"
    }

    //开始评分
    /**
     * 判断输入格式
     *
     */
    @SuppressLint("ClickableViewAccessibility")
    private fun doEvalJob(llComment: LinearLayout, etScore: EditText, position: Int) {
        var score = childAnswerList[position].EvalScore
        etScore.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                //暂存
                //如果数据大于最大值，取最大值
                if (s.toString().isNotEmpty()) {

                    if (s.toString() == ".") {
                        score = BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP)
                    } else {
                        score = s.toString().toBigDecimal().setScale(1, RoundingMode.HALF_UP)
                    }
                    //大于最大值
                    if (childAnswerList[position].TotalScore.compareTo(score) == -1) {
                        score = childAnswerList[position].TotalScore.setScale(1, RoundingMode.HALF_UP)
                        MyToast.showToast("最大数值不得超于分值");
                    }
                    if (score.multiply(BigDecimal.valueOf(10)).divideAndRemainder(BigDecimal.valueOf(5))[1].compareTo(ZERO) == 0) {
                        childAnswerList[position].EvalScore = score
                        saveData(position)
                    }
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })

        etScore.setOnTouchListener { v, event ->
            if (event!!.action == MotionEvent.ACTION_UP) {
                val imm: InputMethodManager = mActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS)
            }
            false
        }

        etScore.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                mActivity.isChange = true
                childAnswerList[position].State = 2
                llComment.background = mActivity.resources.getDrawable(R.drawable.bg_subject_view)
            } else {
                if (score.multiply(BigDecimal.valueOf(10)).divideAndRemainder(BigDecimal.valueOf(5))[1].compareTo(ZERO) != 0) {
                    MyToast.showToast("请输入0.5的倍数!")
                    score = childAnswerList[position].EvalScore
                }
                etScore.setText(score.toString())
            }
        }

        etScore.setOnEditorActionListener { _, i, _ ->
            if (i == EditorInfo.IME_ACTION_NEXT) {
                MyToast.showToast("此功能已禁用!")
                return@setOnEditorActionListener true
            }
            false
        }
    }

    private fun saveData(position: Int) {
        //找到学生ID
        //找到试题ID
        //找到小题序号
        //存入EvalScore，State，Rate
        //已知哪个学生的哪一题的答案，还需知道是
        for (i in mActivity.evalBody.quesList.indices) {
            //遍历所有学生，找到对应的学生ID和对应的试题ID,确定对应的小题
            for (j in mActivity.evalBody.quesList[i].stuAnswerList!!.indices) {
                val stuAnswer = mActivity.evalBody.quesList[i].stuAnswerList!![j]
                if (stuAnswer.StuID == childAnswerList[position].StuId && stuAnswer.QuesID == childAnswerList[position].QuesID) {
                    //遍历答题点，找到对应的答题点，赋值
                    //sortIndex Type == 0
                    for (z in stuAnswer.ChildAnswerList.indices) {
                        if (stuAnswer.ChildAnswerList[z].SortIndexType == 0) {
                            if (stuAnswer.ChildAnswerList[z].ChildIndex == childAnswerList[position].ChildIndex) {
                                stuAnswer.ChildAnswerList[z].EvalScore = childAnswerList[position].EvalScore
                                stuAnswer.ChildAnswerList[z].State = childAnswerList[position].State
                                stuAnswer.ChildAnswerList[z].ScoreRate =
                                        childAnswerList[position].EvalScore
                                                .divide(childAnswerList[position].TotalScore, 2, ROUND_HALF_UP)
                                for (t in stuAnswer.ChildAnswerList[z].ItemList.indices) {
                                    stuAnswer.ChildAnswerList[z].ItemList[t].EvalScore = childAnswerList[position].EvalScore
                                    stuAnswer.ChildAnswerList[z].ItemList[t].State = childAnswerList[position].State
                                    stuAnswer.ChildAnswerList[z].ItemList[t].TotalScore = childAnswerList[position]
                                            .TotalScore
                                            .divide(stuAnswer.ChildAnswerList[z].ItemList.size.toBigDecimal(), 2, ROUND_HALF_UP)

                                    stuAnswer.ChildAnswerList[z].ItemList[t].ScoreRate = childAnswerList[position]
                                            .ScoreRate
                                }
                            }
                        } else {
                            //sortIndexType == 1
                            for (t in stuAnswer.ChildAnswerList[z].ItemList.indices) {
                                if (stuAnswer.ChildAnswerList[z].ItemList[t].ChildIndex == childAnswerList[position].ChildIndex && stuAnswer.ChildAnswerList[z].ItemList[t].ItemIndex == childAnswerList[position].ItemIndex) {
                                    stuAnswer.ChildAnswerList[z].ItemList[t].EvalScore = childAnswerList[position].EvalScore
                                    stuAnswer.ChildAnswerList[z].ItemList[t].State = childAnswerList[position].State
                                    stuAnswer.ChildAnswerList[z].ItemList[t].ScoreRate = childAnswerList[position].EvalScore
                                            .divide(childAnswerList[position].TotalScore, 2, ROUND_HALF_UP)

                                }
                            }
                        }
                    }
                }
            }
        }
    }

    override fun getItemCount(): Int {
        return childAnswerList.size
    }

    override fun getItemViewType(position: Int): Int {
        return position
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    interface OnItemClickListener {
        fun onItemClickPlay(position: Int, path: String?)
    }

    fun setOnItemClickListener(listener: OnItemClickListener) {
        this.onItemClickListener = listener
    }

    fun setChangeListener(changeListener: ChangeListener) {
        this.changeListener = changeListener
    }

    public fun getChildAnswerList(): MutableList<ItemXMark> {
        return childAnswerList
    }
}